import * as defaults from "../msui-utils/msui-default";
import { ref, reactive } from "vue";
class MsuiFormItemModel {
  constructor({ label = "", name, parent } = {}) {
    this.parent = parent;
    this.name = name;
    this.template = "AInput";
    this.show = ref(true);
    this.attrs = {
      bind: {},
      vOn: {},
    };
    this.bind = {};
    this.init({
      label,
      name,
    });
  }
  init(bind) {
    if (defaults[this.template]) {
      this.attrs.bind = { ...defaults[this.template] };
      this.attrs.bind.placeholder = "请输入" + bind.label;
    }
    this.bind.name = bind.name;
    this.bind.label = bind.label;
  }
  setShow(boolean) {
    this.show.value = boolean;
    return this;
  }
  type({ bind = {}, vOn = {}, template = "aInput" } = options) {
    this.attrs = {
      bind: { ...this.attrs.bind, ...bind },
      vOn: { ...this.attrs.vOn, ...vOn },
    };
    if (bind.options && bind.options instanceof Promise) {
      this.attrs.bind.options = reactive([]);
      bind.options.then((res) => {
        this.attrs.bind.options = reactive(res);
      }).catch((err) => {
        this.attrs.bind.options = reactive([]);
      });
    }
    this.template = template;
    return this;
  }
  setBind(bind) {
    this.bind = { ...bind, ...this.bind };
    return this;
  }
  setAttrsBind(bind) {
    for (let key in bind) {
      this.attrs.bind[key] = bind[key];
    }
    return this;
  }
  addRules(rules) {
    if (this.bind.rules === undefined) {
      this.bind.rules = [...rules];
    } else {
      this.bind.rules = [...this.bind?.rules, ...rules];
    }
    return this;
  }
  isRequired() {
    const rule = { required: true, message: this.attrs.bind.placeholder };
    if (this.bind.rules === undefined) {
      this.bind.rules = [rule];
    } else {
      this.bind.rules = this.bind.rules.push(rule);
    }
    return this;
  }
  setValue(value) {
    this.parent.bind.model[this.name] = value;
    return this;
  }
  getValue() {
    return this.parent.bind.model[this.name];
  }
}

export default MsuiFormItemModel;
